﻿namespace DimensionsHelper.Client.WinUi.Services;

public class PageService : IPageService
{
    private readonly Dictionary<string, Type> _pages = [];

    public PageService()
    {
        Configure<TableFormatterViewModel, TableFormatterPage>();
        Configure<TaskInformationViewModel, TaskInformationPage>();
        Configure<SettingsViewModel, SettingsPage>();
        Configure<TableReplacementsViewModel, TableReplacementsPage>();
        Configure<MetadataDocumentViewModel, MetadataDocumentPage>();
        Configure<QueryViewModel, QueryPage>();
        Configure<TableFormatterTableOptionsViewModel, TableFormatterTableOptionsPage>();
        Configure<TableFormatterFilesViewModel, TableFormatterFilesPage>();
        Configure<TableReorderMapViewModel, TableReorderMapPage>();
        Configure<QueryDataViewModel, QueryDataPage>();
    }

    public Type GetPageType(string key)
    {
        Type? pageType;
        lock (_pages)
        {
            if (!_pages.TryGetValue(key, out pageType))
            {
                throw new ArgumentException($"Page not found: {key}. Did you forget to call PageService.Configure?");
            }
        }

        return pageType;
    }

    private void Configure<TViewModel, TView>()
        where TViewModel : ObservableObject
        where TView : Page
    {
        lock (_pages)
        {
            string? key = typeof(TViewModel).FullName!;
            if (_pages.ContainsKey(key))
            {
                throw new ArgumentException($"The key {key} is already configured in PageService");
            }

            Type? type = typeof(TView);
            if (_pages.ContainsValue(type))
            {
                throw new ArgumentException(
                    $"This type is already configured with key {_pages.First(p => p.Value == type).Key}");
            }

            _pages.Add(key, type);
        }
    }
}